package com.haohan.jingyuan.customer.service;

import com.haohan.jingyuan.common.enums.ErrorEnum;
import com.haohan.jingyuan.common.exception.BusinessException;
import com.haohan.jingyuan.common.util.EntityUtil;
import com.haohan.jingyuan.customer.dao.CustomerInfoMapper;
import com.haohan.jingyuan.customer.dao.CustomerTagMapper;
import com.haohan.jingyuan.customer.dto.req.CreateTagRequest;
import com.haohan.jingyuan.customer.dto.req.DeleteTagRequest;
import com.haohan.jingyuan.customer.dto.req.QueryTagListRequest;
import com.haohan.jingyuan.customer.dto.req.UpdateTagRequest;
import com.haohan.jingyuan.customer.dto.resp.TagInfoResp;
import com.haohan.jingyuan.customer.dto.resp.TagListResp;
import com.haohan.jingyuan.customer.entity.CustomerInfo;
import com.haohan.jingyuan.customer.entity.CustomerTag;
import com.haohan.jingyuan.customer.helper.TagRespHelper;
import com.haohan.jingyuan.gateway.holder.UserContextHolder;
import com.haohan.jingyuan.util.UuidUtil;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.*;

/**
 * 客户标签服务实现类
 *
 * @ClassName CustomerTagService
 * @Description 客户标签相关业务逻辑实现
 * @Author hexijun
 * @Time 2025/10/30 10:00
 * @Version 1.0
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class CustomerTagService {

    /**
     * 客户标签Mapper
     */
    private final CustomerTagMapper customerTagMapper;

    /**
     * 客户信息Mapper
     */
    private final CustomerInfoMapper customerInfoMapper;

    /**
     * 创建标签
     *
     * @param request 创建标签请求
     * @return 标签信息
     */
    public TagInfoResp createTag(CreateTagRequest request) {
        // 检查标签名称是否已存在（只检查未删除的记录，ukid=0）
        CustomerTag exist = customerTagMapper.findByName(request.getTagName());
        if (exist != null) {
            throw new BusinessException(ErrorEnum.TAG_ALREADY_EXISTS);
        }

        CustomerTag tag = new CustomerTag();
        tag.setTagCode(UuidUtil.generateId("TAG_", 5));
        tag.setTagName(request.getTagName());
        tag.setType(request.getType());
        tag.setRemarks(request.getRemarks());
        // ukid默认为0
        tag.setUkid(0L);
        EntityUtil.setCreateAndModifyInfo(tag, UserContextHolder.getCurrentUserName());

        int result = customerTagMapper.insert(tag);
        if (result <= 0) {
            throw new BusinessException(ErrorEnum.DATABASE_ERROR);
        }
        return TagRespHelper.convert2TagInfoResp(tag);
    }

    /**
     * 更新标签
     *
     * @param request 更新标签请求
     * @return 标签信息
     */
    public TagInfoResp updateTag(UpdateTagRequest request) {
        Long id = Long.parseLong(request.getId());
        CustomerTag current = customerTagMapper.findById(id);
        if (current == null) {
            throw new BusinessException(ErrorEnum.TAG_NOT_FOUND);
        }
        CustomerTag byName = customerTagMapper.findByName(request.getTagName());
        if (byName != null && !Objects.equals(byName.getId(), id)) {
            throw new BusinessException(ErrorEnum.TAG_ALREADY_EXISTS);
        }

        current.setTagName(request.getTagName());
        current.setType(request.getType());
        current.setRemarks(request.getRemarks());
        EntityUtil.setModifyInfo(current, UserContextHolder.getCurrentUserName());

        int result = customerTagMapper.updateById(current);
        if (result <= 0) {
            throw new BusinessException(ErrorEnum.DATABASE_ERROR);
        }
        return TagRespHelper.convert2TagInfoResp(current);
    }

    /**
     * 删除标签
     *
     * @param request 删除标签请求
     * @return 是否成功
     */
    public boolean deleteTag(DeleteTagRequest request) {
        Long id = Long.parseLong(request.getId());
        CustomerTag current = customerTagMapper.findById(id);
        if (current == null) {
            throw new BusinessException(ErrorEnum.TAG_NOT_FOUND);
        }

        // 预筛：SQL LIKE，后置：Java 精确匹配
        List<CustomerInfo> mayUsed = customerInfoMapper.selectByTagsLike(current.getTagCode());
        if (mayUsed != null && !mayUsed.isEmpty()) {
            for (CustomerInfo info : mayUsed) {
                if (isTagUsedExactly(info.getTags(), current.getTagCode())) {
                    throw new BusinessException(ErrorEnum.TAG_IN_USE);
                }
            }
        }

        // 设置ukid为记录主键id
        current.setUkid(id);
        EntityUtil.setModifyInfo(current, UserContextHolder.getCurrentUserName());
        int result = customerTagMapper.updateById(current);
        return result > 0;
    }

    /**
     * 查询标签列表
     *
     * @param request 查询标签列表请求
     * @return 标签列表
     */
    public TagListResp queryTagList(QueryTagListRequest request) {
        // 根据type查询标签（type为必填字段）
        List<CustomerTag> list = customerTagMapper.selectByType(request.getType());
        return TagRespHelper.convert2TagListResp(list);
    }

    /**
     * 精确判断给定标签是否存在于逗号分隔的tags中
     *
     * @param tags 逗号分隔的标签code字符串
     * @param code 标签编码
     * @return 是否存在
     */
    private boolean isTagUsedExactly(String tags, String code) {
        if (tags == null || tags.trim().isEmpty()) {
            return false;
        }
        String[] arr = tags.split(",");
        for (String token : arr) {
            if (code.equals(token != null ? token.trim() : null)) {
                return true;
            }
        }
        return false;
    }
}


